﻿CREATE PROCEDURE [ServiceEngine].[CreateEntityGroup]
 @Name nvarchar(400),
 @Description ntext = null, 
 @EntityTypeID smallint,
 @ID uniqueidentifier OUTPUT
AS
BEGIN
 DECLARE @ErrorMessage NVARCHAR(4000);
 DECLARE @ErrorSeverity INT;
 DECLARE @ErrorState INT;
 SET NOCOUNT ON;

 IF @ID IS NULL 
  SET @ID = newid();

 BEGIN TRY
  BEGIN TRANSACTION

  INSERT INTO ServiceEngine.EntityGroups (EntityGroupID, EntityTypeID)
  VALUES (@ID, @EntityTypeID)

  BEGIN TRY
   INSERT INTO ServiceEngine.Names (EntityID, EntityTypeID, EntityName, EntityDescription)
   VALUES (@ID, 11, @Name, @Description)
  END TRY
  BEGIN CATCH

   SELECT 
    @ErrorMessage = 'Attempt to insert Group with duplicate name failed',
    @ErrorSeverity = 11,
    @ErrorState = ERROR_STATE();

   RAISERROR (@ErrorMessage, 
        @ErrorSeverity,
        1);
  END CATCH

  COMMIT TRANSACTION
 END TRY
 BEGIN CATCH
  SELECT 
   @ErrorMessage = ERROR_MESSAGE(),
   @ErrorSeverity = ERROR_SEVERITY(),
   @ErrorState = ERROR_STATE();

  IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;

  RAISERROR (@ErrorMessage, 
       @ErrorSeverity,
       1);
 END CATCH

END

GO

